package com.apes.autoparts.supplier.longsky;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.supplier.platform.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.MapUtil;
import org.elasticsearch.index.IndexNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

public abstract class LongSkyApi<T, R> extends SupplierPlatformApi<T, R> {

    @Autowired
    SupplierPlatformRepository supplierPlatformRepository;
    @Autowired
    LongSkyRepository longSkyRepository;

    private SupplierPlatform supplierPlatform;

    private SupplierPlatform getSupplierPlatform(){
        if (this.supplierPlatform != null) return this.supplierPlatform;

        SupplierPlatform supplierPlatform = SpringManager.getBean(SupplierPlatformRepository.class).findOne(
                JpaDsl.toCriteriaByEq(
                        "code", getSource()
                )
        ).orElse(null);
        if (supplierPlatform == null) throw new RuntimeException("未找到当前平台：" + getSource());

        this.supplierPlatform = supplierPlatform;
        return this.supplierPlatform;
    }

    LongSkyApi() {
        this.source = SupplierPlatformConst.LONG_SKY;
    }

    @Override
    public R getProductStock(SimpleRequest request) {
        return null;
    }

    @Override
    public void synTotal(SupplierPlatformItem supplierPlatformItem) {
        if (supplierPlatformItem.getState().equals("debugging")) {
            delete(supplierPlatformItem);
        }
        getStockByPage(supplierPlatformItem, false);
    }

    @Override
    public void synIncrement(SupplierPlatformItem supplierPlatformItem) {
        getStockByPage(supplierPlatformItem, true);
    }


    /***
     * 分页获取库存
     */
    private void getStockByPage(SupplierPlatformItem supplierPlatformItem, boolean IsDiff) {
        String Token = getToken();

        // 获取总的分页数
        int pages = getStock(supplierPlatformItem, Token, -1, IsDiff, null, null).getInteger("Count");

        // 循环获取每一页的数据
        JSONArray splitterArray = new JSONArray();
        for (int i = 0; i < pages; i++) {
            splitterArray.clear(); // 清空数据
            JSONArray array = getStock(supplierPlatformItem, Token, i, IsDiff, null, null).getJSONArray("Data");

            for (int j = 0 , len = array.size(); j < len; j++){
                JSONObject tempJson = array.getJSONObject(j);
                tempJson.put("supplierPlatformItem", MapUtil.mapper(
                        "id", supplierPlatformItem.getId()
                ));
                tempJson.put("batch", DateUtil.format(new Date(),DateUtil.SHOW_DATE_NUMBER_FORMAT));
                splitterArray.add(tempJson);
            }
            JSONObject param = new JSONObject();

            // 预防数据超过1000条
            int size = splitterArray.size();
            for (int k = 0; k <= size / 1000; k++) {
                List subList =  (List)splitterArray.subList(k * 1000, k != (size / 1000 ) ? (k + 1) * 1000 : size);
                param.put("data", subList);
                param.put("supplierPlatformItemId", supplierPlatformItem.getId());
                if (!IsDiff) param.put("action", "synTotal");
                else param.put("action", "synIncrement");
                if (i +1 == pages) param.put("lastData", true);
                if (supplierPlatformItem.getState().equals("debugging")) {
                    MQUtil.publish("auto.longSky.debugging", "长远接口调试数据", param);
                //SpringManager.getBean(DomainService.class).invoke("auto.inHeart.debugging", param);
                }else
                    MQUtil.publish("auto.longSky.handHeap", "长远接口处理堆数据", param);
//                SpringManager.getBean(DomainService.class).invoke("auto.longSky.handHeap", param);
                // 切片处理数据防止数据量过大造成堵塞

            }
        }
    }


    /***
     * 登录获取Token
     */
    private String getToken() {
        long timestamp = new Date().getTime();

        Map param = MapUtil.mapper(
                "Json", MapUtil.mapper(
                        "AppKey", getSupplierPlatform().getAppKey(),
                        "AppSign", getAppSign(timestamp),
                        "Timestamp", timestamp
                )
        );

        return resolveError(requestCore(getSupplierPlatform().getUrl() + "Login", param, null)).getString("Data");
    }


    /***
     * 获取库存
     */
    private JSONObject getStock(SupplierPlatformItem supplierPlatformItem, String Token, int PageNum, boolean IsDiff, String NNO, String[] ids) {

        String ID = ids != null ? String.join(",", ids) : "";

        Map param = MapUtil.mapper(
                "Token", Token,
                "Json", MapUtil.mapper(
                        "UserID", supplierPlatformItem.getAccessKey(),
                        "Data", MapUtil.mapper(
                                "NNO", NNO != null ? NNO : "",
                                "ID", ID,
                                "PageNum", PageNum,
                                "IsDiff", IsDiff
                        )
                )
        );
        return resolveError(requestCore(getSupplierPlatform().getUrl() + "EC_GetIsto", param,null));
    }


    /***
     * 处理返回值
     */
    private JSONObject resolveError(JSONObject param) {

        if (param.getIntValue("ErrorCode") != 0) {
            if (param.getIntValue("ErrorCode") == 4) throw new RuntimeException("当前Token已失效");
            throw new RuntimeException(param.getString("Msg"));
        }

        return param;
    }

    /***
     * 获取签名
     */
    private String getAppSign(long timestamp) {
        return md5(md5((getSupplierPlatform().getAppKey() + String.valueOf(timestamp)).toUpperCase()) + getSupplierPlatform().getAppSecret());
    }

    private String md5(String inputText) {
        return MD5Util.encrypt(inputText, "gbk").toUpperCase();
    }

    /***
     * 模拟长远接口
     */

    public void simulationApi(SupplierPlatformItem supplierPlatformItem, JSONObject jo) {


        // 循环获取每一页的数据
        JSONArray splitterArray = new JSONArray();
        JSONArray array = jo.getJSONArray("data");
        for (int j = 0 , len = array.size(); j < len; j++) {
            JSONObject tempJson = array.getJSONObject(j);
            tempJson.put("supplierPlatformItem", MapUtil.mapper(
                    "id", supplierPlatformItem.getId()
            ));
            tempJson.put("batch", DateUtil.format(new Date(),DateUtil.SHOW_DATE_NUMBER_FORMAT));
            splitterArray.add(tempJson);
//            SpringManager.getBean(DomainService.class).invoke("auto.longSkyService.handleRow", tempJson);
        }

        // 切片处理数据防止数据量过大造成堵塞
        SpringManager.getBean(DomainService.class).invoke("auto.longSky.handleRows", splitterArray);
        }

    /**
     * 调试阶段
     * @param supplierPlatformItem
     */
    @Override
    public void test(SupplierPlatformItem supplierPlatformItem) {

    }

    public void delete(SupplierPlatformItem supplierPlatformItem) {
        try {
            SpringManager.getBean(LongSkyDebugRepository.class).deleteLongSkyDebugBySupplierPlatformItem(supplierPlatformItem.getId());
        } catch (IndexNotFoundException e) {
            e.printStackTrace();
        }
    }
}
